package com.hankol.material.adapter

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.utils.*
import com.hankol.material.R
import com.hankol.material.api.MaterialConstants
import com.hankol.material.api.MaterialConstants.Companion.downloadFile
import com.hankol.material.bean.CreateFolderBean
import com.hankol.material.bean.MaterialContentInfo
import com.hankol.material.bean.TabConfigure
import com.baselibrary.bean.download.ShowUIUtils
import com.hankol.material.help.MaterialHelp
import com.hankol.material.help.PopUtils
import com.hankol.material.view.HKPlayVideo
import com.hankol.material.viewmodel.MaterialContentViewModel
import com.tencent.rtmp.TXVodPlayer

/**
 * @description:
 * @author: 关忆北丶
 * @date :   2021/10/18 16:03
 */
class ContentListVideoAdapter( private val myFragment: BaseFragment, private val viewModel: MaterialContentViewModel, val owner: LifecycleOwner, private var searchContent: String, private var activity: Activity) : RecyclerView.Adapter<ContentListVideoAdapter.ContentListVideoHolder>() {

    private var mContext: Context? = null
    var mList: ArrayList<MaterialContentInfo.FileLibsBean.DataBean> = arrayListOf()
    var mLastVodPlayer: TXVodPlayer? = null
    var mLastViewHkVideoBinding: View? = null
    var mHKPlayVideo: HKPlayVideo? = null
    var tHandler: Handler? = null
    var collectionFolderId: Long = 0//收藏夹的ID，从收藏夹进入必传
    val userIds: Int by lazy { SpUtils.getInstance().userId }
    var netState: Boolean = false//本次进入是否已经提示网络情况
    private var itemPosition: Int = -1
    fun setData(list: List<MaterialContentInfo.FileLibsBean.DataBean>) {
        mList.clear()
        mList.addAll(list)
        notifyDataSetChanged()
    }

    fun addData(list: List<MaterialContentInfo.FileLibsBean.DataBean>) {
        if (list.isNotEmpty()) {
            mList.addAll(list)
            notifyDataSetChanged()
        }
    }

    fun setListener() {
        viewModel.mOnScrollStateChanged = object : MaterialContentViewModel.OnScrollStateChanged {
            override fun onStateChanged(startPosition: Int, endPosition: Int) {
                if (itemPosition < startPosition || itemPosition > endPosition) {
                    mHKPlayVideo?.let {
                        if (it.txVodPlayer != null && it.txVodPlayer.isPlaying) {
                            it.setVideoPlaySate(false)
                        }
                    }
                }
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentListVideoHolder {
        mContext = parent.context
        val inflate =
            LayoutInflater.from(mContext).inflate(R.layout.item_contentlist_video, parent, false)

        return ContentListVideoHolder(inflate)
    }

    override fun onBindViewHolder(holder: ContentListVideoHolder, position: Int) {
        val bean = mList[position]
        bean.collectionFolderId = collectionFolderId
        holder.mHKPlayVideo.setCover(bean)
        if (TextUtils.isEmpty(searchContent)) {
            holder.mHKPlayVideo.setVideoTitle("${bean.name}.${bean.desc}")
        } else {
            holder.mHKPlayVideo.setVideoTitle(ColorTextUtils.setKeyWordColor(mContext, bean.name, searchContent, R.color.color_c39d67))
        }
        holder.mHKPlayVideo.setVideoTime(bean.videoSec)
        holder.mIvContentListVideoLike.setImageResource(if (bean.isHasCollect == 1) R.drawable.ic_material_true_like else R.drawable.ic_material_false_like)

        if (collectionFolderId > 0) {
            //id存在则是从收藏夹进入
            holder.mLlLike.visibility = View.GONE
            holder.mLlContentListVideoDet.visibility = View.VISIBLE
            holder.mLlContentListVideoMove.visibility = View.VISIBLE
        } else {
            holder.mLlLike.visibility = View.VISIBLE
            holder.mLlContentListVideoDet.visibility = View.GONE
            holder.mLlContentListVideoMove.visibility = View.GONE
        }


        holder.mHKPlayVideo.setVideoUrl(bean.fileUrl, activity)
        holder.mHKPlayVideo.initListener()
        holder.mHKPlayVideo.continuedPlay(this, {
            // netState = true
        }, {
            mHKPlayVideo = holder.mHKPlayVideo
            itemPosition = position
        }, { _, _ ->
            viewModel.reqAddShareCount(bean.id, 2)
        })
        holder.mHKPlayVideo.setPlayListener(this, {
            mHKPlayVideo = holder.mHKPlayVideo
            itemPosition = position
        }, { _, _ ->
            viewModel.reqAddShareCount(bean.id, 2)
        })

        holder.initListener(bean, position)
        holder.setIsRecyclable(false)
    }

    fun onDestroy() {
        mHKPlayVideo?.onDestroy()
    }

    fun deactivate() {
        mHKPlayVideo?.deactivate()
    }

    override fun getItemCount(): Int {
        return mList.size
    }

    inner class ContentListVideoHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var mLlDownload: LinearLayout = itemView.findViewById(R.id.ll_contentListVideo_download)
        var mLlLike: LinearLayout = itemView.findViewById(R.id.ll_contentListVideo_like)
        var mLlShare: LinearLayout = itemView.findViewById(R.id.ll_contentListVideo_share)
        var mIvContentListVideoLike: ImageView =
            itemView.findViewById(R.id.iv_contentListVideo_like)
        var mLlContentListVideoDet: LinearLayout =
            itemView.findViewById(R.id.ll_contentListVideo_det)
        var mLlContentListVideoMove: LinearLayout =
            itemView.findViewById(R.id.ll_contentListVideo_move)
        var mHKPlayVideo: HKPlayVideo = itemView.findViewById(R.id.HKPlayVideo)

        fun initListener(bean: MaterialContentInfo.FileLibsBean.DataBean, position: Int) {
            mLlLike.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return@setOnClickListener
                }
                if (bean.isHasCollect == 0) {
                    //收藏
                    myFragment.activity?.let {
                        viewModel.collectionMaterial(it, owner, bean.id, object : APIResponse<CreateFolderBean>(this) {
                            override fun onSuccess(result: CreateFolderBean?, json: String?) {
                                ToastUtils.showShort(mContext, "收藏成功")
                                bean.isHasCollect = 1
                                mIvContentListVideoLike.setImageResource(R.drawable.ic_material_true_like)
                                SensorsDataManager.instance.materialCollection(bean.name,MaterialConstants.MATERIAL_VIDEO)
                            }

                            override fun onFailed(message: String?) {
                                ToastUtils.showShort(mContext, "网络异常，收藏失败")
                            }
                        })
                    }
                } else {
                    //取消收藏
                    viewModel.loadCancelCollection(bean.collectionFolderId, bean.id, object : APIResponse<Boolean>(this) {
                        override fun onSuccess(result: Boolean?, json: String?) {
                            ToastUtils.showShort(mContext, "已取消收藏")
                            bean.isHasCollect = 0
                            mIvContentListVideoLike.setImageResource(R.drawable.ic_material_false_like)
                            if (collectionFolderId > 0) {
                                //文件夹进入
                                itemPosition = position
                                EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.VIDEO.tabConfig)
                                EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.VIDEO.tabConfig)
                            }
                        }

                        override fun onFailed(message: String?) {
                            ToastUtils.showShort(mContext, "网络异常，取消收藏失败")
                        }
                    })
                }
            }

            mLlContentListVideoDet.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return@setOnClickListener
                }
                //删除
                viewModel.loadCancelCollection(bean.collectionFolderId, bean.id, object : APIResponse<Boolean>(this) {
                    override fun onSuccess(result: Boolean?, json: String?) {
                        ToastUtils.showShort(mContext, "删除成功")
                        if (collectionFolderId > 0) {
                            itemPosition = position
                            EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.VIDEO.tabConfig)
                            EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.VIDEO.tabConfig)
                        }
                    }

                    override fun onFailed(message: String?) {
                        ToastUtils.showShort(mContext, "网络异常，删除失败")
                    }
                })
            }

            mLlContentListVideoMove.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return@setOnClickListener
                }
                viewModel.moveMaterial(myFragment.attachActivity, owner, bean.id, bean.collectionFolderId, object : APIResponse<Boolean>(this) {
                    override fun onSuccess(result: Boolean?, json: String?) {
                        ToastUtils.showShort(mContext, "移动成功")
                        if (collectionFolderId > 0) {
                            itemPosition = position
                            EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.VIDEO.tabConfig)
                            EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.VIDEO.tabConfig)
                        }

                    }

                    override fun onFailed(message: String?) {
                        ToastUtils.showShort(mContext, "网络异常，移动失败")
                    }
                })
            }

            mLlShare.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return@setOnClickListener
                }
                viewModel.shareMaterial(myFragment.attachActivity, bean.id, bean.name, bean.thumbnail, false, TabConfigure.VIDEO.tabConfig)
            }

            mLlDownload.setOnClickListener {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    ToastUtils.showShort(mContext, "请勿频繁操作")
                    return@setOnClickListener
                }
                viewModel.reqMaterialAuthenticity(bean.id, object : APIResponse<Boolean>(this) {
                    override fun onSuccess(result: Boolean?, json: String?) {
                        PopUtils.showMaterialVideoLoad(myFragment.attachActivity, ShowUIUtils.byteToString(bean.fileSize), View.OnClickListener {
                            if (it.id == R.id.ll_file_videoPhoneDown) {
                                PermissionsUtils.getInstance().chekPermissions(myFragment.attachActivity, PermissionCollection.FILE.getPermissionList(), object : PermissionsCall() {
                                    override fun permissionsPass() {
                                        viewModel.reqAddShareCount(bean.id, 0)
                                        MaterialConstants.downloadFile(myFragment.attachActivity, bean.fileUrl, "${bean.name}.${bean.desc}", bean.thumbnail, bean.fileSize, bean.type)
                                    }
                                })
                            } else {
                                CommonUtil.contentClipboard(mContext, bean.fileUrlVideoOriginal, "复制成功，请粘贴到浏览器中下载")
                            }
                        })
                    }
                })

            }
        }
    }

    fun removeCurrentData() {
        if (itemPosition != -1) {
            mList.removeAt(itemPosition)
            notifyDataSetChanged()
        }
    }

}
